package com.xyzwps.paimon.furina.modules.post

import com.xyzwps.paimon.furina.common.AppErrorCode.*
import com.xyzwps.paimon.furina.common.AppException
import com.xyzwps.paimon.furina.modules.post.entity.PostCollection
import com.xyzwps.paimon.furina.modules.post.service.PostCollectionService
import com.xyzwps.paimon.furina.modules.post.service.PostService
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transaction
import org.springframework.stereotype.Service

@Service
class PostCollectionApplication(
    private val collectionService: PostCollectionService,
    private val postService: PostService,
    private val db: Database
) {

    fun getCollectionById(id: Long, currentUserId: Long): PostCollectionDTO = transaction(db) {
        val c = collectionService.findById(id, currentUserId)
            ?: throw AppException(POST_COLLECTION_NOT_FOUND)
        PostCollectionDTO(c, updatable = true)
    }

    fun getCollections(currentUserId: Long): List<PostCollectionDTO> = transaction(db) {
        collectionService.findByUserId(currentUserId).map { PostCollectionDTO(it, updatable = true) }
    }

    fun delete(id: Long, currentUserId: Long) = transaction(db) {
        if (collectionService.delete(id, currentUserId)) {
            postService.deleteByCollectionId(id, currentUserId)
        }
    }

    fun update(id: Long, currentUserId: Long, payload: PostCollectionSavePayload): PostCollectionDTO = transaction(db) {
        val c = collectionService.update(id, currentUserId, payload.title)
        PostCollectionDTO(c, updatable = true)
    }

    fun create(currentUserId: Long, payload: PostCollectionSavePayload): PostCollectionDTO = transaction(db) {
        val c = collectionService.create(currentUserId, payload.title)
        PostCollectionDTO(c, updatable = true)
    }
}